import * as d3 from "d3";
import React from "react";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { useRequest } from "ahooks";
import { CustomDatePicker } from "@/components/ui/datepicker";
import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import ClipLoader from "react-spinners/ClipLoader";
import { Skeleton } from "@/components/ui/skeleton";
import { VbpStatsByCadnI } from "@/types/api";
import { getVbpBatchEndDateList, getVbpStatsByCadn } from "@/api";
import { dayjs } from "@/App";
import { useLocation, useNavigate, useSearchParams } from "react-router-dom";
import BarChartByCadn from "./components/bar_chart_by_cadn_group";
import { useSelector } from "react-redux";
import { useToast } from "@/hooks/use-toast";
import { useStatsParams } from "@/hooks/useStatsParams";
import { RootStateI } from "@/types";

const VbpStats = (): JSX.Element => {
  const location = useLocation();
  const [vbpBatchEndDateList, setVbpBatchEndDateList] = React.useState<
    VbpStatsByCadnI[]
  >([]);
  const [vbpStatsList, setVbpStatsList] = React.useState<VbpStatsByCadnI[]>([]);
  const [totalDays, setTotalDays] = React.useState<number>(0);
  const [elapsedDays, setElapsedDays] = React.useState<number>(0);
  const user = useSelector((state: RootStateI) => state.user);
  const { toast } = useToast();
  const { startDate, endDate, batchEndDate, setStatsParams } = useStatsParams();

  const formSchema = z.object({
    startDate: z.date(),
    endDate: z.date(),
    batchEndDate: z.string(),
  });

  const defaultValues = {
    startDate:
      startDate && dayjs(JSON.parse(startDate)).isValid()
        ? dayjs(JSON.parse(startDate)).toDate()
        : dayjs("2023-01-01").toDate(),
    endDate:
      endDate && dayjs(JSON.parse(endDate)).isValid()
        ? dayjs(JSON.parse(endDate)).toDate()
        : dayjs(new Date()).toDate(),
    batchEndDate: batchEndDate,
  };

  const colorScale: any = d3
    .scaleLinear()
    .domain([0, 1])
    .range(["green", "red"] as any);

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: defaultValues,
  });

  // 2. Define a submit handler.
  function onSubmit(values: z.infer<typeof formSchema>) {
    // Do something with the form values.
    // ✅ This will be type-safe and validated.
    console.log(values);
    const params = new URLSearchParams();
    params.set("startDate", JSON.stringify(values.startDate));
    params.set("endDate", JSON.stringify(values.endDate));
    params.set("batchEndDate", JSON.stringify(values.batchEndDate));
    setStatsParams({
      startDate: JSON.stringify(values.startDate),
      endDate: JSON.stringify(values.endDate),
      batchEndDate: values.batchEndDate,
    });

    runByCadn(params.toString());
  }

  // 获取可视化数据，一次取全部
  const { loading: loadingEndDateList, run: runEndDateList } = useRequest(
    (paramsString: string) => getVbpBatchEndDateList(paramsString),
    {
      manual: false,
      defaultParams: [location.search.replace(/^\?/, "")],
      onSuccess(resp: any, params: any) {
        // console.log(resp);
        setVbpBatchEndDateList(resp.data.data);
      },
      onError(e: any, params: any) {
        toast({
          variant: "destructive",
          title: "获取数据失败",
        });
      },
    }
  );

  // 获取可视化数据，一次取全部
  const { loading: loadingChartData, run: runByCadn } = useRequest(
    (paramsString: string) => getVbpStatsByCadn(paramsString),
    {
      manual: false,
      defaultParams: [location.search.replace(/^\?/, "")],
      onSuccess(resp: any, params: any) {
        console.log(resp);
        setVbpStatsList(resp.data.data);
        if (resp.data.data.length) {
          const startDate = dayjs(resp.data.data[0].startDate);
          const endDate = dayjs(resp.data.data[0].endDate);

          const totalDays = Math.abs(
            Math.round(
              endDate.diff(startDate, "millisecond") / (1000 * 60 * 60 * 24)
            )
          );
          const elapsedDays = Math.abs(
            Math.round(
              dayjs().diff(startDate, "millisecond") / (1000 * 60 * 60 * 24)
            )
          );
          console.log(totalDays);
          console.log(elapsedDays);
          setTotalDays(totalDays);
          setElapsedDays(elapsedDays);
        }
      },
      onError(e: any, params: any) {
        toast({
          variant: "destructive",
          title: "获取数据失败",
        });
      },
    }
  );

  // React.useEffect(() => {
  //   form.reset(defaultValues);
  // }, []);

  return (
    <div className="w-full p-6">
      <div className="w-full py-6 border p-3">
        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(onSubmit)}
            className="flex items-center space-x-4"
          >
            <FormField
              control={form.control}
              name="startDate"
              render={({ field }) => (
                <FormItem>
                  {/* <FormLabel>开始时间</FormLabel> */}
                  <FormControl>
                    <CustomDatePicker
                      placeholder="开始时间"
                      value={field.value}
                      onChange={field.onChange}
                      startMonth={dayjs().subtract(2, "year").toDate()}
                      endMonth={dayjs().add(1, "year").toDate()}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="endDate"
              render={({ field }) => (
                <FormItem>
                  {/* <FormLabel>结束时间</FormLabel> */}
                  <FormControl>
                    <CustomDatePicker
                      placeholder="结束时间"
                      value={field.value}
                      onChange={field.onChange}
                      startMonth={dayjs().subtract(2, "years").toDate()}
                      endMonth={dayjs().add(1, "years").toDate()}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="batchEndDate"
              render={({ field }) => (
                <FormItem>
                  <Select
                    defaultValue={field.value}
                    onValueChange={field.onChange}
                  >
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue placeholder="选择批次结束时间" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      <SelectItem value="%" key="%">
                        <span className="font-bold">全部批次</span>
                      </SelectItem>
                      {vbpBatchEndDateList.map((item: any) => {
                        // console.log(
                        //   dayjs(item.endDate).format("YYYY-MM-DD HH:mm:ss")
                        // );
                        return (
                          <SelectItem
                            value={dayjs(item.endDate).format(
                              "YYYY-MM-DD HH:mm:ss"
                            )}
                            key={dayjs(item.endDate).format(
                              "YYYY-MM-DD HH:mm:ss"
                            )}
                          >
                            {dayjs(item.endDate).format("YYYY-MM-DD")}
                          </SelectItem>
                        );
                      })}
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />
            <Button type="submit">查询</Button>
          </form>
        </Form>
      </div>

      <div className="py-6 min-h-screen">
        <div id="chartContainer" className="w-full">
          <div className="text-center">
            <h3 className="text-2xl font-bold">按通用名分组完成情况</h3>
            <div className="w-full flex justify-center">
              {loadingChartData ? (
                <div className="w-full flex justify-center">
                  <Skeleton className="w-[1024px] h-[768px] flex justify-center items-center">
                    数据加载中
                    <ClipLoader
                      loading={loadingChartData}
                      size={50}
                      aria-label="Loading Spinner"
                      data-testid="loader"
                    />
                  </Skeleton>
                </div>
              ) : vbpStatsList.length > 0 ? (
                <div>
                  <span>
                    {batchEndDate == "%" ? (
                      ""
                    ) : (
                      <span
                        style={{ color: colorScale(elapsedDays / totalDays) }}
                      >
                        当前批次从
                        {dayjs(vbpStatsList[0].startDate)!.format(
                          "YYYY-MM-DD"
                        )}{" "}
                        到{dayjs(vbpStatsList[0].endDate)!.format("YYYY-MM-DD")}
                        ，已经过了
                        <span className="font-bold">
                          {elapsedDays}/{totalDays}
                        </span>
                      </span>
                    )}{" "}
                  </span>
                  <BarChartByCadn
                    data={vbpStatsList}
                    watermarkText={user.username}
                    statsStartDate={
                      startDate
                        ? dayjs(JSON.parse(startDate)).toDate()
                        : new Date()
                    }
                    statsEndDate={
                      endDate ? dayjs(JSON.parse(endDate)).toDate() : new Date()
                    }
                    selectedBatch={batchEndDate} // 确认某个批准
                  />
                </div>
              ) : (
                <Skeleton className="w-[1024px] h-[768px] flex justify-center items-center">
                  没有查询结果
                </Skeleton>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default VbpStats;
